import React from "react";
import { FlatList, StyleSheet, Text } from "react-native";
import { TouchableOpacity, View } from "react-native-ui-lib";
import { commonStyles } from "../../configs/commonStyle";
import navigator from "../../utils/navigator";
import BasePage from "../BasePage";
import ListSeparator from "../common/ListSeparator";
import ListEmpty from "../common/ListEmpty";
import { inject, observer } from "mobx-react";
import Events from "../../utils/events";
import moment from "moment";
import { call, setClipboardContent } from "../../utils/util";

/**
 * 投诉订单
 */
@inject("userStore", "appStore")
@observer
export default class ComplaintOrderList extends BasePage {

  constructor(props) {
    super(props);
    this.pageNo = 1;
    this.pageSize = 15;
    this.totalPages = 0;
    this.isLoading = false;
    this.isFirst = true;
    this.state = {
      isRefreshing: false,
      showFoot: 0,
      showEmpty: false,
      dataList: [],
      delyStartTime: this.props.delyStartTime,
      delyEndTimeEnd: this.props.delyEndTimeEnd,
      ratio: "0%",
      countall: 0,
      count: 0,
      ordState: this.props.ordState,
    };
  }

  componentDidMount() {
    super.componentDidMount();
    this.loadData(false);
    this.refreshOrderList = Events.subscribe("RefreshComplaintOrderList", () => this._renderRefresh(false));
  }

  componentWillUnmount() {
    super.componentWillUnmount();
    this.refreshOrderList && this.refreshOrderList.remove();
  }

  loadByDate = (delyStartTime, delyEndTimeEnd) => {
    this.setState({ delyStartTime, delyEndTimeEnd }, () => this._renderRefresh(false));
  };

  loadByState = (ordState) => {
    this.setState({ ordState }, () => this._renderRefresh(false));
  };

  loadData = (showLoading = true) => {
    const { dataList, delyStartTime, delyEndTimeEnd, ordState } = this.state;
    this.isLoading = true;
    let params = {
      // pageNum: this.pageNo,
      // pageSize: this.pageSize,
      token: global.token,
      delyStartTime: `${delyStartTime} 00:00:00`,
      delyEndTimeEnd: `${delyEndTimeEnd} 23:59:59`,
      showLoading,
      ordState,
    };
    axios.get(this.props.api, { params })
      .then(res => {
        this.isLoading = false;
        // let tempArr = [];
        // let showf;
        // this.totalPages = res.count / this.pageSize + (res.count % this.pageSize > 0 ? 0 : 1);
        // if (this.pageNo == 1) {
        //   tempArr = res.list || [];
        //   showf = 0;
        // } else {
        //   tempArr = dataList.concat(res.list);
        //   showf = (this.pageNo == this.totalPages) ? 1 : 0;
        // }
        this.setState({
          dataList: res.list || [],
          isRefreshing: false,
          showEmpty: IsNullOrEmpty(res.list),
        });
      })
      .catch(e => {
        logger("error", e);
        this.isLoading = false;
        this.setState({
          isRefreshing: false,
          showEmpty: true,
        });
      });
  };


  _onEndReached = async () => {
    //如果是正在加载中或到底了，则返回
    if (this.state.showFoot != 0) {
      return;
    }
    //如果当前页大于或等于总页数，那就是到最后一页了，返回
    if (this.pageNo == this.totalPages || this.totalPages == 0) {
      return;
    } else {
      this.pageNo++;
    }
    //底部显示正在加载更多数据
    this.setState({ showFoot: 2 });
    //获取数据
    this.loadData();
  };

  // 下拉刷新
  _renderRefresh = (isRefreshing = true) => {
    // 不处于 下拉刷新
    if (this.isLoading === false && !this.state.isRefreshing) {
      this.setState({
        isRefreshing,
      });
      this.pageNo = 1;
      this.totalPages = 0;
      this.loadData();
    }
  };

  getAuditState = (audit_state) => {
    switch (audit_state) {
      case 1:
        return "待处理";
      case 2:
        return "申诉成功";
      case 3:
        return "申诉失败";
      default:
        return "未申诉";
    }
  };

  render_item = ({ item, index }) => {
    let reason, reasonResult;
    if (this.props.relationType == 1) {
      reason = "退款原因";
      reasonResult = item?.apply_reason;
    } else if (this.props.relationType == 2) {
      reason = "退订原因";
      reasonResult = item?.apply_reason;
    } else {
      reason = "投诉原因";
      reasonResult = item?.complaint_content;
    }

    return (
      <View>
        <View style={styles.titleWrap}>
          <TouchableOpacity activeOpacity={1} onPress={() => setClipboardContent(item?.xmbz_no)}>
            <Text style={commonStyles.text_black_14}>单号：{item?.xmbz_no}</Text>
          </TouchableOpacity>
        </View>
        <View style={styles.contentWrap}>
          <View style={styles.itemWrap}>
            <Text style={commonStyles.text_black_13}>配送终止时间</Text>
            <Text
              style={commonStyles.text_blue_13}>{item.delivery_end_time ? moment(item.delivery_end_time).format("MM-DD HH:mm") : ""}</Text>
          </View>
          <View style={styles.itemWrap}>
            <Text style={commonStyles.text_black_13}>实际完成时间</Text>
            <Text
              style={commonStyles.text_black_13}>{item.received_time ? moment(item.received_time).format("MM-DD HH:mm") : ""}</Text>
          </View>
          <View style={styles.itemWrap}>
            <Text style={commonStyles.text_black_13}>联系电话</Text>
            {
              item.receiver_phone && !item.receiver_phone.includes("*") ?
                <TouchableOpacity onPress={() => call(item?.receiver_phone,item?.ordNo)}>
                  <Text style={commonStyles.text_black_13}>{item?.receiver_phone}</Text>
                </TouchableOpacity>
                : <Text style={commonStyles.text_black_13}>{item?.receiver_phone}</Text>
            }
          </View>
          <View style={{ ...styles.itemWrap, alignItems: "flex-start" }}>
            <Text style={commonStyles.text_black_13}>{reason}</Text>
            <View marginL-20 flex right>
              <Text style={commonStyles.text_black_13}>{reasonResult}</Text>
            </View>
          </View>
          <View style={styles.itemWrap}>
            <Text style={commonStyles.text_black_13}>处理结果</Text>
            <View marginL-10 flex right>
              <Text style={commonStyles.text_black_13}>{item?.audit_text}</Text>
            </View>
          </View>
          {/*<View style={styles.itemWrap}>*/}
          {/*  <Text style={commonStyles.text_black_13}>责任人</Text>*/}
          {/*  <Text style={commonStyles.text_black_13}>配送部</Text>*/}
          {/*</View>*/}
          <View style={styles.itemWrap}>
            <Text style={commonStyles.text_black_13}>处理状态</Text>
            <Text style={commonStyles.text_black_13}>{this.getAuditState(item.audit_state)}</Text>
          </View>
        </View>
        {
          IsNullOrEmpty(item.audit_state) ?
            <View style={styles.line} /> : null
        }
        {
          IsNullOrEmpty(item.audit_state) && item.datediff <= 1 ?
            <View style={styles.reasonWrap}>
              <TouchableOpacity activeOpacity={1} throttleTime={1000} style={styles.btn}
                                onPress={() => navigator.navigate("OrderComplaintAppeal", {
                                  xmbzNo: item.xmbz_no,
                                  relation_id: item.relation_id,
                                  relationType: this.props.relationType,
                                })}>
                <Text style={commonStyles.text_black}>我要申诉</Text>
              </TouchableOpacity>
            </View>
            : null
        }
      </View>
    );
  };


  render() {
    const { dataList, isRefreshing } = this.state;
    return (
      <View flex>
        <FlatList
          data={dataList}
          onRefresh={this._renderRefresh}
          showsVerticalScrollIndicator={false}
          refreshing={isRefreshing}
          extraData={this.state}
          style={{}}
          contentContainerStyle={{ flexGrow: 1 }}
          keyExtractor={(item, index) => "menu_" + index}
          renderItem={this.render_item}
          ItemSeparatorComponent={() => <ListSeparator height={0.5} backgroundColor={"#F7F7F7"} />}
          ListEmptyComponent={() => <ListEmpty showEmpty={this.state.showEmpty} />}
          // onEndReached={this._onEndReached}
          // onEndReachedThreshold={0.1}
          // ListFooterComponent={() => <ListFooter showFoot={this.state.showFoot} page={this.pageNo} />}
        />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  titleWrap: {
    justifyContent: "space-between",
    flexDirection: "row",
    alignItems: "center",
    borderTopLeftRadius: 4,
    borderTopRightRadius: 4,
    backgroundColor: "#F9D63B",
    marginHorizontal: 15,
    paddingHorizontal: 15,
    paddingVertical: 10,
    marginTop: 15,
  },

  contentWrap: {
    backgroundColor: "white",
    marginHorizontal: 15,
    paddingHorizontal: 15,
    paddingVertical: 10,
  },
  reasonWrap: {
    borderBottomLeftRadius: 4,
    borderBottomRightRadius: 4,
    backgroundColor: "white",
    marginHorizontal: 15,
    paddingHorizontal: 15,
    paddingVertical: 10,
    alignItems: "flex-end",
  },
  itemWrap: {
    justifyContent: "space-between",
    flexDirection: "row",
    alignItems: "center",
    paddingVertical: 6,
  }
  , line: {
    height: 1,
    backgroundColor: "#EFEFEF",
    marginHorizontal: 15,
  },
  btn: {
    width: 80,
    height: 30,
    ...commonStyles.center,
    backgroundColor: "#F9D63B",
    borderRadius: 5,
  },
});
